<?php

namespace app\home\controller;

use app\common\model\Cart as CartMd;
use nsCms\Form;

class Cart extends Common
{
    
    public $uid;
    
    public function initialize()
    {
        parent::initialize();
        if (!session('uid')) {
            header('location:' . url('/login'));
        }
        $this->uid = session('uid');
    }
    
    public function index(CartMd $cartMd)
    {
        $list = $cartMd->where('uid', $this->uid)->select();
        $total = $cartMd->where('uid', $this->uid)->sum('price');
        $this->assign('list', $list);
        $this->assign('total', $total);
        return $this->fetch();
    }
    
    //购物车
    public function cart(CartMd $cartMd)
    {
        $id = input('id/i', 0);
        $num = input('num/i', 1);
        $do = input('do', 'get');
        if ($do == 'add') {
            $gs = db('goods')->find($id);
            $cart = $cartMd->where("product_id", $id)->where('uid', $this->uid)->find();
            if ($cart) {
                $u_cart['num'] = $cart['num'] + $num;
                $u_cart['price'] = $cart['product_price'] * $cart['num'];
                $cartMd->where('id', $cart['id'])->update($u_cart);
            } else {
                $data = [];
                $data['uid'] = $this->uid;
                $data['product_id'] = $gs['id'];
                $data['product_pic'] = $gs['img'];
                $data['product_title'] = $gs['title'];
                $data['product_price'] = $gs['price'];
                $data['create_time'] = time();
                $data['update_time'] = time();
                $data['num'] = $num;
                $data['price'] = $data['product_price'] * $data['num'];
                $cartMd->insert($data);
            }
            return outJson();
        } elseif ($do == 'update') {
            $data = $cartMd->find($id);
            $num = $_REQUEST['zt'] == 1 ? $data['num'] + 1 : $data['num'] - 1;
            $u_data['num'] = $num;
            $u_data['update_time'] = time();
            $r_data['subtotal'] = $u_data['price'] = bcmul($data['product_price'], $num, 2);
            $total = $cartMd->where('uid', $this->uid)->sum('price');
            $r_data['total'] = bcmul($total,1,2);
            $cartMd->where('id', $id)->update($u_data);
            return outJson(1,'',$r_data);
        } elseif ($do == 'del') {
            $cartMd->where('id', $id)->delete();
            return outJson();
        } elseif ($do == 'get') {
            $list = $cartMd->where('uid', $this->uid)->select();
            $data['list'] = $list;
            $data['count'] = count($list);
            $total = $cartMd->where('uid', $this->uid)->sum('price');
            $data['total'] = bcmul($total,1,2);
            return outJson(1, '', $data);
        }
    }
    
}